import { Context, Next } from 'koa'
import service from '../service/user.service'
import { addRoleParams, ctxUser, IGetListParams, IUser } from '@/types/user.types'
import { baseSuccess } from '@/constants/resonponse'
import userService from '../service/user.service'

class UserController {
  /**
   * 新增用户
   * @param ctx
   * @param next
   */
  public async create(ctx: Context, next: Next) {
    // 获取用户请求传递参数
    const user = ctx.request.body as unknown as IUser

    // 查询数据
    ctx.body = await service.create(user)
  }

  /**
   * 用户关联角色
   * @param ctx
   * @param next
   */
  public async addRole(ctx: Context, next: Next) {
    const params = ctx.request.body as unknown as addRoleParams
    try {
      await service.addRole(params)
      ctx.body = baseSuccess
    } catch (e) {
      console.log(e)
      ctx.body = {
        code: 80001,
        msg: e.message
      }
    }
  }

  /**
   * 查询用户权限菜单
   * @param ctx
   * @param next
   */
  public async getMenu(ctx: Context, next: Next) {
    const { id } = ctx.user as unknown as ctxUser
    try {
      const res = await service.getMenu(id)
      ctx.body = {
        code: 200,
        data: res[0]
      }
    } catch (e) {
      console.log(e)
      ctx.body = {
        code: 80001,
        msg: e.message
      }
    }
  }

  /**
   * 查询用户权限菜单
   * @param ctx
   * @param next
   */
  public async getList(ctx: Context, next: Next) {
    const params = ctx.request.query as unknown as IGetListParams
    try {
      const [rows]: any= await userService.getList(params)
      if (rows.length < 0) {
        return ctx.app.emit('error', ctx, '获取菜单列表错误')
      }
      const [counter]: any = await userService.getListCount(params)

      if (!counter.length) {
        return ctx.app.emit('error', ctx, '获取count错误')
      }
      const res = {
        list: rows,
        count: counter[0].count
      }
      return ctx.app.emit('success', ctx, res)
    } catch (e) {
      const u = e as Error
      return ctx.app.emit('systemError', ctx, u.message)
    }
  }
}

export default new UserController()